package com.ladlee.parking.validate.custom;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;

@Slf4j
public class EnumCheckValidator implements ConstraintValidator<EnumCheck, Object> {

    EnumCheck enumCheck;

    /**
     * 验证
     *
     * @param value   注解标记的值
     * @param context
     * @return
     */
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (ObjectUtil.isNull(value)) {
            return !this.enumCheck.required();
        }
        // value的类型
        Class<?> valueClass = value.getClass();
        try {
            // 通过反射执行枚举类中validation方法
            Method method = this.enumCheck.enumClass().getMethod(this.enumCheck.enumMethod(), valueClass);
            Boolean result = (Boolean) method.invoke(null, value);
            if (result == null) {
                return false;
            }
            return result;
        } catch (Exception e) {
            log.error("自定义验证失败");
        }
        return false;
    }

    @Override
    public void initialize(EnumCheck enumCheck) {
        this.enumCheck = enumCheck;
    }
}
